require('es6-promise').polyfill();
import Vue from 'vue'
import App from './app'
import axios from 'axios'
import VueRouter from 'vue-router'
import Routers from './routers'
import Loading from 'toon-ui/lib/components/loading'
import util from '../../assets/js/util'
import Toast from 'toon-ui/lib/components/toast'
import appConfig from '../../assets/js/app.config'
import   '../../assets/css/common.css'
import   './index.css'
const  HOST = configM.comUrl ;
const  TOON_CODE = util.getQueryStringHr('code')  || configM.code || "" ;
const  CITY_CODE = util.getQueryStringHr('cityCode')  || configM.cityCode || "" ;

// 全局配置
Vue.config.debug = false
Vue.config.devtools = false
Vue.config.silent = true
Vue.prototype.$util = util
var axiosInstance = axios.create()
Vue.prototype.$http = axiosInstance

//========创建vue实例==========
let  initVue = ()=>{
  // 并且配置路由规则
  Vue.use(VueRouter)
  const router = new VueRouter({
    mode: 'hash',
    routes: Routers
  })
  router.beforeEach((to, from, next) => {
    if( !navigator.onLine ){
         Toast({
          message: '无网络连接，请稍后重试',
          duration: 1000, // 持续时间，默认3000毫秒
        });
        return ;
    }
    next() ;
  })
  new Vue({
    router,
    render: h => h(App)
  }).$mount('#app')

}

//========axiosInstance==========
axiosInstance.defaults.baseURL =HOST;
axiosInstance.defaults.timeout = 10000;
axiosInstance.defaults.loading = true;
axiosInstance.defaults.sessionId = true;
axiosInstance.defaults.headers.post['content-type'] = 'application/json;charset=utf-8';
// Add a request interceptor请求拦截
axiosInstance.interceptors.request.use(function (config) {
  console.log(config)
  if(config.loading) {
    Loading.open('');
  }
  if(config.sessionId) {
    config.headers.sessionId = util.sessionId();
  }
  return config;
}, function (error) {
  Loading.close('')
  return Promise.reject(error);
});
// Add a response interceptor请求响应拦截
axiosInstance.interceptors.response.use(function (response) {
  Loading.close('')
  var code=response.data&&response.data.meta.code
  if(code==appConfig.respCode.SESSION_TIMEOUT||code==appConfig.respCode.TOON_CODE_TIMEOUT||code==appConfig.respCode.TOKEN_TIMEOUT){
    Toast({
      message: '操作超时',
      duration: 3000, // 持续时间，默认3000毫秒
    });
    setTimeout(function(){
      util.sessionId("")
      var params={"functionType":1};
      window.location.href = "toon://mwap/window?params="+ JSON.stringify(params);
    },2000)
    return Promise.reject(response.data)
  }else{
    return response.data;
  }
}, function (error) {
  Loading.close('')
  if(error.response){
  }else{
    console.log('Error: ',error.message);
  }
  return Promise.reject(error);
});

//========axiosInstance==========
/**
 * 授权getSessionIdByTOON_CODE
 */
 (function(){
   if( util.sessionId() || location.hash === '#/introduction'){
     return  initVue();
   }else if( !TOON_CODE && !CITY_CODE ){
     util.updateApp('随手拍');
   }
   let api = "/session/getSessionIdByToonCode" ,
       param =  {toonCode:TOON_CODE, random : Math.random()} ;
       if(util.getQueryStringHr('cityCode')){
         api = "/session/getSessionIdByCityCode" ;
         param =  {cityCode:util.getQueryStringHr('cityCode') } ;
       }
   axiosInstance.post(HOST+ api , param  )
     .then(function (res) {
       //code解密失败,下载新的北京通
       if(res.meta.code == appConfig.respCode.CODE_INVALID ){
         util.updateApp('随手拍');
       }
       if(res.meta.code == "0" && res.data && res.data.sessionId){
         util.sessionId(res.data.sessionId);
         initVue();
       }
     })
     .catch(function (err) {
       console.log(err);
     });
 })();


